package com.student.controller;

import com.student.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/select")  //学生选课功能
public class SelectCoursesController {
    @Autowired
    private SelectionDAO selectionDAO;

    @Autowired
    private StudentDAO studentDAO;

    @Autowired
    private CourseDAO courseDAO;

    @PostMapping("/add")
    public ResponseEntity<Selection> select(String serialNumber,int courseId){  // 选课：添加一个选课的一个关系   这里必须确定一个学生和一堂课
        if(!studentDAO.existsBySerialNumber(serialNumber)||!courseDAO.existsById(courseId))
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        Student student = studentDAO.findStudentBySerialNumber(serialNumber);

        Selection selection = new Selection();
        selection.setStuId(student.getId()); //代码有点乱
        selection.setCourseId(courseId);
        return new ResponseEntity<>(selectionDAO.save(selection),HttpStatus.OK);
    }

    @GetMapping("/findCourseByStuId")  //通过学生Id找某个学生上了那些课
    public ResponseEntity<?> findCourseByStuId(int stuId){
        if(!selectionDAO.existsByStuId(stuId))
            return new ResponseEntity<>("尚未选课",HttpStatus.BAD_REQUEST);
        return new ResponseEntity<>(selectionDAO.findAllByStuId(stuId),HttpStatus.OK);
    }

    @GetMapping("/findStudentByCourseId")  //通过课程Id找某个课有哪些学生
    public ResponseEntity<?> findStudentByCourseId(int courseId){
        if(!selectionDAO.existsByCourseId(courseId))
            return new ResponseEntity<>("尚未有人选择此课程",HttpStatus.BAD_REQUEST);
        return new ResponseEntity<>(selectionDAO.findAllByCourseId(courseId),HttpStatus.OK);
    }

}
